const express = require("express");
const { db } = require("../database");
const { CustomerAuth } = require("../middles");
const { avatar } = require("../upload");
const { sign } = require("../jwt");
const { makePassword, checkPassword } = require("../utils");

const { validate, validators } = require("../validate");

// 无需身份验证的路由
const notAuthRouter = express.Router();
notAuthRouter.post(
  "/login",
  validate([validators.username, validators.password]),
  async (req, res) => {
    const { username, password } = req.body;
    // 根据用户名查询用户信息
    const manager = await db.findOne(
      "select * from manager where username = ?",
      [username]
    );
    // 判断密码是否输入正确
    if (manager && checkPassword(password, manager.password)) {
      // 在会话（session）中保存用户信息
      req.session.userId = manager.id;
      // 签发 token 给客户端代码
      const token = sign({ userId: manager.id });
      return res.send({
        success: true,
        object: manager,
        token,
      });
    }
    res.send({ success: false, message: "用户名或密码错误！" });
  }
);

const router = express.Router();
// CustomerAuth 中间件实现对登录用户的验证，如果验证通过，就会有 req.user 属性。
router.use(CustomerAuth);
// 定义路由
router
  .get("/profile", async (req, res) => {
    res.send({
      success: true,
      object: req.user,
    });
  })
  // 添加新管理员
  .post(
    "/",
    avatar.single("avatar"),
    validate([validators.username, validators.password, validators.nickname]),
    async (req, res) => {
      const { username, password, nickname } = req.body;
      const exist = await db.findOne(
        "select * from manager where username = ?",
        [username]
      );
      if (exist)
        return res.send({
          success: false,
          errors: { username: ["该用户名已经存在！"] },
        });
      const results = await db.select(
        "insert into manager (username, nickname, password, avatar) values (?,?,?,?)",
        [
          username,
          nickname,
          makePassword(password),
          req.file?.filename ? "/avatars/" + req.file?.filename : null,
        ]
      );
      const manager = await db.findOne("select * from manager where id = ?", [
        results.insertId,
      ]);
      res.send({
        success: true,
        object: manager,
      });
    }
  )
  // 修改管理员信息
  .put(
    "/:mid",
    avatar.single("avatar"),
    validate([validators.nickname]),
    async (req, res) => {
      const { mid } = req.params,
        { avatar, nickname } = req.body;
      let manager = await db.findOne("select * from manager where id = ?", [
        mid,
      ]);
      if (!manager)
        return res.send({ success: false, message: "未能找到该用户信息！" });
      await db.query(
        "update manager set nickname = ?, avatar = ? where id = ?",
        [nickname, avatar ? avatar : "/avatar/" + req.file.filename, mid]
      );
      manager = await db.findOne("select * from manager where id = ?", [mid]);
      res.send({
        success: true,
        message: "用户信息更新成功！",
        object: manager,
      });
    }
  )
  // 查询所有管理员信息
  .get(
    "/",
    validate([validators.limit, validators.offset]),
    async (req, res) => {
      const { limit = 10, offset = 0 } = req.query;
      // 获取查询的总数
      let sql = `select count(*) as count from manager`;
      const { count } = await db.findOne(sql);
      const results = await db.select("select * from manager");
      res.send({
        success: true,
        query: {
          count,
          limit,
          offset,
          page: offset / limit + 1,
          results,
        },
      });
    }
  );

const registerRouter = (app) => {
  app.use("/manager", notAuthRouter);
  app.use("/manager", router);
};

module.exports = { registerRouter };
